<template>
<template v-if="user">
  <van-image
      class="avatar"
      round
      width="7rem"
      height="7rem"
      :src="user.avatarUrl"
      fit="cover"
      @click="showActionSheet = true"
  />

  <!-- 添加 ActionSheet -->
  <van-action-sheet
      v-model:show="showActionSheet"
      :actions="actions"
      @select="onSelect"
      cancel-text="取消"
      close-on-click-action
  />

  <van-cell title="昵称" is-link arrow-direction="right" :value="user.userName" @click="toEdit('userName', '昵称', user.userName)" />
  <van-cell title="账号" is-link arrow-direction="right" :value="user.userAccount" @click="toEdit('userAccount', '账号', user.userAccount)" />
  <van-cell title="性别" is-link arrow-direction="right" :value="formatGender(user.gender)" @click="toEdit('gender', '性别', formatGender(user.gender))" />
  <van-cell title="电话" is-link arrow-direction="right" :value="user.phone" @click="toEdit('phone', '电话', user.phone)" />
  <van-cell title="邮箱" is-link :value="user.email" />
  <van-cell title="星球ID" is-link :value="user.planetCode"/>
  <van-cell title="注册时间" is-link :value="formatTime(user.createTime)" />
</template>

</template>

<script setup lang="ts">

import {useRouter} from "vue-router";
import {onMounted, ref} from 'vue';
import {showFailToast, showImagePreview} from "vant";
import {getLoginUser} from "../services/user.ts";
import {setCurrentUser} from "../global/user.ts";
import {formatGender, formatTime} from "../services/format.ts";

// 添加响应式状态
const showActionSheet = ref(false);

const user = ref();

onMounted( async () => {
  // 从后端获取用户信息然后存入缓存
  const res = await getLoginUser();
  if (res.code === 0) {
    user.value = res.data;
    setCurrentUser(user.value)
  } else {
    showFailToast('请先进行登录')
    await router.replace('/user/login');
  }
})

const router = useRouter();

const toEdit = (editKey: string, editName: string, currentValue: string) => {
  router.push({
    path: '/user/edit',
    query: {
      editKey,
      editName,
      currentValue,
    }
  })
}

const actions = [
  { name: '查看头像' },
  { name: '更改头像' }
];

// 添加操作处理逻辑
const onSelect = (action: { name: string }) => {
  if (action.name === '查看头像') {
    showImagePreview({
      images: [user.value.avatarUrl],
      // 关闭按钮
      //closeable: true,
    });
  } else if (action.name === '更改头像') {
    // 触发隐藏的文件输入
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = 'image/*';
    fileInput.onchange = (e: Event) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (event) => {
          user.value.avatarUrl = event.target?.result as string;
        };
        reader.readAsDataURL(file);
      }
    };
    fileInput.click();
  }
};

</script>

<style scoped>

.avatar {
  margin: 1rem auto;
  display: block;
}

</style>